package downstream

import (
	"context"
	"google.golang.org/grpc"
	"google.golang.org/grpc/status"
	"pay/api/open"
	"pay/internal/conf"
	"pay/internal/constant"
	"pay/pkg/ecode"
	"pay/pkg/log"
	"pay/pkg/network"
	"pay/pkg/request_key"
	"time"
)

func newOpenClient(ctx context.Context, addr string) (
	client open.OpenServiceClient, err error) {
	var conn *grpc.ClientConn
	dialCtx, cancel := request_key.NewOutGoingContext(ctx, time.Second*1)
	defer cancel()
	conn, err = grpc.DialContext(dialCtx, addr, grpc.WithInsecure(),
		grpc.WithUnaryInterceptor(network.ClientInterceptor(
			"wxpay", time.Second*3, openErrorTranslator)))
	if err != nil {
		err = ecode.AppendMessage(constant.ErrRemoteError, "授权管理服务地址无法建立有效连接, err=%s", err.Error())
		log.FromContext(ctx).Warnw(err.Error())
		return
	}
	client = open.NewOpenServiceClient(conn)
	return
}

func openErrorTranslator(err error) (errCode *ecode.ErrorCode) {
	rpcStatus := status.Convert(err)
	errCode = ecode.AppendMessage(
		constant.ErrRemoteError, "授权管理服务调用失败: %s", rpcStatus.Message())
	return
}

func (d *Downstream) QueryAppIds(ctx context.Context, sgIds []int64) (appMap map[uint32]string, err error) {
	if d.openClient == nil {
		if d.openClient, err = newOpenClient(
			ctx, conf.Conf.Downstream.OpenAddress); err != nil {
			return
		}
	}
	var resp *open.QueryWechatAppIDsReply
	if resp, err = d.openClient.QueryWechatAppIDs(ctx, &open.QueryWechatAppIDsRequest{
		BrandIds: sgIds}); err != nil {
		return
	}
	appMap = make(map[uint32]string)
	for i, sgId := range sgIds {
		appMap[uint32(sgId)] = resp.AppIds[i]
	}
	return
}
